// 认证控制器
import authService from '../services/authService.ts';
import { successResponse, errorResponse } from '../utils/response.ts';
import type { FastifyRequest, FastifyReply } from 'fastify';

// 定义注册请求体类型
interface RegisterRequestBody {
  username: string;
  email: string;
  password: string;
}

// 定义登录请求体类型
interface LoginRequestBody {
  username: string;
  password: string;
}

/**
 * 用户注册控制器
 * 处理用户注册请求
 * @param {FastifyRequest} request - Fastify请求对象，包含用户名、邮箱和密码
 * @param {FastifyReply} reply - Fastify响应对象
 * @returns {Promise<FastifyReply>} 注册结果响应
 */
async function register(request: FastifyRequest<{ Body: RegisterRequestBody }>, reply: FastifyReply): Promise<FastifyReply> {
  try {
    const { username, email, password } = request.body;
    const result = await authService.registerUser(username, email, password);
    return reply.send(successResponse(result, '注册成功'));
  } catch (err) {
    return reply.code(400).send(errorResponse((err as Error).message, 400));
  }
}

/**
 * 用户登录控制器
 * 处理用户登录请求
 * @param {FastifyRequest} request - Fastify请求对象，包含用户名和密码
 * @param {FastifyReply} reply - Fastify响应对象
 * @returns {Promise<FastifyReply>} 登录结果响应，包含认证令牌
 */
async function login(request: FastifyRequest<{ Body: LoginRequestBody }>, reply: FastifyReply): Promise<FastifyReply> {
  try {
    const { username, password } = request.body;
    const result = await authService.loginUser(username, password);
    return reply.send(successResponse(result, '登录成功'));
  } catch (err) {
    return reply.code(401).send(errorResponse((err as Error).message, 401));
  }
}

export default { register, login };



